document.addEventListener('DOMContentLoaded', function() {
    const mainTitleInput = document.getElementById('mainTitle');
    const subTitleInput = document.getElementById('subTitle');
    const rightContentInput = document.getElementById('rightContent');
    const bottomTagInput = document.getElementById('bottomTag');
    const bottomRightInput = document.getElementById('bottomRight');
    // 页码输入已移除
    const watermarkInput = document.getElementById('watermark');
    const topTitleInput = document.getElementById('topTitle');
    const tocContentInput = document.getElementById('tocContent');
    const bgColorInput = document.getElementById('bgColor');
    const highlightColorInput = document.getElementById('highlightColor');
    
    const generateBtn = document.getElementById('generateBtn');
    const downloadBtn = document.getElementById('downloadBtn');
    const previewCard = document.getElementById('previewCard');
    
    // 初始化预览
    updatePreview();
    
    // 监听输入变化
    mainTitleInput.addEventListener('input', updatePreview);
    subTitleInput.addEventListener('input', updatePreview);
    rightContentInput.addEventListener('input', updatePreview);
    bottomTagInput.addEventListener('input', updatePreview);
    bottomRightInput.addEventListener('input', updatePreview);
    // 页码输入监听已移除
    watermarkInput.addEventListener('input', updatePreview);
    topTitleInput.addEventListener('input', updatePreview);
    tocContentInput.addEventListener('input', updatePreview);
    bgColorInput.addEventListener('input', updatePreview);
    highlightColorInput.addEventListener('input', updatePreview);
    
    // 生成图片
    generateBtn.addEventListener('click', generateImage);
    
    // 下载图片
    downloadBtn.addEventListener('click', downloadImage);
    
    // 更新预览
    function updatePreview() {
        // 更新主标题
        const mainTitleLines = mainTitleInput.value.split('\n');
        const mainTitleElement = document.querySelector('.main-title');
        mainTitleElement.innerHTML = '';
        
        mainTitleLines.forEach((line, index) => {
            const div = document.createElement('div');
            // 为最后一行添加高亮
            if (index === mainTitleLines.length - 1) {
                div.innerHTML = `<span class="highlight">${line}</span>`;
            } else {
                div.textContent = line;
            }
            mainTitleElement.appendChild(div);
        });
        
        // 更新副标题
        document.querySelector('.sub-title').textContent = subTitleInput.value;
        
        // 更新右侧内容
        const rightContentLines = rightContentInput.value.split('\n');
        const rightContentElement = document.getElementById('rightContentDisplay');
        rightContentElement.innerHTML = '';
        
        rightContentLines.forEach(line => {
            const div = document.createElement('div');
            div.textContent = line;
            rightContentElement.appendChild(div);
        });
        
        // 更新底部标签
        document.querySelector('.bottom-tag').textContent = bottomTagInput.value;
        
        // 更新右下角文字
        document.querySelector('.bottom-right-text').textContent = bottomRightInput.value;
        
        // 页码更新已移除
        
        // 更新水印
        const watermarks = document.querySelectorAll('.watermark-text');
        watermarks.forEach(watermark => {
            watermark.textContent = watermarkInput.value;
        });
        
        // 更新顶部标题
        document.querySelector('.top-title').textContent = topTitleInput.value;
        
        // 更新目录内容
        const tocContentElement = document.getElementById('tocContentDisplay');
        tocContentElement.innerHTML = '';
        
        const tocLines = tocContentInput.value.split('\n').filter(line => line.trim() !== '');
        // 最多显示11条目录项
        const maxTocItems = 11;
        const displayedTocLines = tocLines.slice(0, maxTocItems);
        
        displayedTocLines.forEach(line => {
            // 尝试自动识别目录和页码
            let title = '';
            let page = '';
            
            // 检查是否已经使用|分隔符
            if (line.includes('|')) {
                const parts = line.split('|');
                title = parts[0] || '';
                page = parts.length > 1 ? parts[1] : '';
            } else {
                // 尝试识别末尾的数字作为页码
                const match = line.match(/^(.*?)(?:\s+\.+\s*|\s+)(\d+)$/);
                if (match) {
                    title = match[1].trim();
                    page = match[2].trim();
                } else {
                    // 如果没有明显的页码，尝试查找最后一个数字组
                    const lastNumberMatch = line.match(/(.*?)(\d+)\s*$/);
                    if (lastNumberMatch) {
                        title = lastNumberMatch[1].trim();
                        page = lastNumberMatch[2].trim();
                    } else {
                        // 如果没有找到页码，整行作为标题
                        title = line.trim();
                    }
                }
            }
            
            // 限制标题长度为20个字符
            if (title.length > 20) {
                title = title.substring(0, 20) + "...";
            }
            
            const tocItem = document.createElement('div');
            tocItem.className = 'toc-item small';
            
            const tocText = document.createElement('span');
            tocText.className = 'toc-text';
            tocText.textContent = title;
            
            const tocPage = document.createElement('span');
            tocPage.className = 'toc-page';
            tocPage.textContent = page;
            
            tocItem.appendChild(tocText);
            tocItem.appendChild(tocPage);
            tocContentElement.appendChild(tocItem);
        });
        
        // 更新背景颜色
        previewCard.style.backgroundColor = bgColorInput.value;
        
        // 更新高亮颜色
        const highlightElements = document.querySelectorAll('.highlight');
        highlightElements.forEach(element => {
            element.style.backgroundColor = highlightColorInput.value;
        });
    }
    
    // 生成图片
    function generateImage() {
        // 确保在生成图片前更新预览
        updatePreview();
        
        // 确保预览卡片可见
        previewCard.style.display = 'block';
        
        html2canvas(previewCard, {
            backgroundColor: null,
            scale: 2, // 提高图片质量
            logging: false,
            useCORS: true
        }).then(canvas => {
            // 显示生成的图片
            const imgUrl = canvas.toDataURL('image/png');
            
            // 创建一个临时图片元素来显示生成的图片
            const imgPreview = document.createElement('img');
            imgPreview.src = imgUrl;
            imgPreview.style.width = '100%';
            imgPreview.style.borderRadius = '10px';
            imgPreview.style.boxShadow = '0 4px 15px rgba(0, 0, 0, 0.1)';
            
            // 清除之前的预览图片
            const oldImgPreview = document.querySelector('.preview-container img');
            if (oldImgPreview) {
                oldImgPreview.remove();
            }
            
            // 隐藏原始预览卡片
            previewCard.style.display = 'none';
            
            // 添加新的预览图片
            document.querySelector('.preview-container').appendChild(imgPreview);
            
            // 启用下载按钮
            downloadBtn.disabled = false;
            
            // 存储图片URL供下载使用
            downloadBtn.setAttribute('data-img-url', imgUrl);
        }).catch(error => {
            console.error('生成图片时出错:', error);
            alert('生成图片失败，请重试');
        });
    }
    
    // 下载图片
    function downloadImage() {
        const imgUrl = downloadBtn.getAttribute('data-img-url');
        if (!imgUrl) {
            alert('请先生成图片');
            return;
        }
        
        const link = document.createElement('a');
        link.download = '页面截图_' + new Date().getTime() + '.png';
        link.href = imgUrl;
        link.click();
    }
});